<template>
	<!-- #ifdef MP-WEIXIN -->
	<view class="container">
		<view class="userinfo">
			<view class="userAvatarUrl"><open-data type="userAvatarUrl"></open-data></view>
			<open-data type="userNickName"></open-data>
			<view class="text">为了使您体验完整功能请点击下方登录</view>
		</view>
		<button type="primary" class="btn" lang="zh_CN" open-type="getUserInfo" @getuserinfo="getuserinfo">登录</button>
	</view>
	<!-- #endif -->
</template>

<script>
import routeUtil from '@/util/routeUtil.js';
import { MappAuthLogin } from '@/api/login.js';
import { mapMutations } from 'vuex';
export default {
	data() {
		return {
			url: '../index/index',
			count: 1
		};
	},
	onLoad(e) {
		// #ifdef H5
		uni.switchTab({
			url: this.url
		});
		// #endif
		// #ifdef MP-WEIXIN
		if (e.returnUrl) {
			this.url = e.returnUrl;
		}
		console.log(this.url)
		// #endif
	},
	// #ifdef MP-WEIXIN
	methods: {
		...mapMutations('user', ['login', 'logout','removeSessionId']),
		getuserinfo: async function(e) {
			var that = this;
			if (e.detail.errMsg === 'getUserInfo:ok') {
				var [fail, success] = await uni.checkSession();
				var code = '';
				var errMsg = '';
				if (fail || !that.$store.state.user.sessionId) {
					var [error, loginRes] = await uni.login({
						provider: 'weixin'
					});
					code = loginRes.code;
					errMsg = loginRes.errMsg;
				}
				if (success || errMsg === 'login:ok') {
					var authRes = await MappAuthLogin({
						AuthProvider: 'WeChatMiniProgram',
						ProviderAccessCode: JSON.stringify({
							appId: that.$store.state.common.appid,
							code: code,
							sessionId: that.$store.state.user.sessionId,
							encryptedData: e.detail.encryptedData,
							iv: e.detail.iv
						})
					}).catch(() => {
						uni.showToast({
							title: '请重新点击登录',
							duration: 3000
						});
						that.removeSessionId();
					});
					if (authRes) {
						this.login({ 
							token: authRes.accessToken, 
							sessionId: authRes.sessionId,
							clientUserName: authRes.clientUserName,
						});
					}
				
					routeUtil.returnUrlHandler(that.url);
				}
			}
		}
	}
	// #endif
};
</script>

<style lang="scss" scoped>
/* #ifdef MP-WEIXIN */
.userinfo {
	display: flex;
	width: 100%;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	margin-top: 20vh;
}
.userAvatarUrl {
	margin-bottom: 5vh;
	width: 30vw;
	height: 30vw;
	border-radius: 50%;
	overflow: hidden;
}
.text {
	margin-top: 30rpx;
	font-weight: 800;
}
.btn {
	position: fixed;
	bottom: 0;
	width: 100%;
}
/* #endif */
</style>
